﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using org.smslib.modem;
using org.smslib.modem.athandler;
using org.smslib;
using System.Threading;
using System.Text.RegularExpressions;
using System.Diagnostics;
using SmsUI.SmsHelper;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Logging;

namespace SMSCore
{
    public class DTGS800IPModemGateway : IPModemGateway
    {
        // private static object SYNC_Commander = new object();

        private int readTimes = 0;

        public DTGS800IPModemGateway(string id, string ipName, int ipPort, string manufacturer, string model) :
            base(id, ipName, ipPort, manufacturer, model)
        {
            AATHandler at = new ATHandler_AnyData_DTGS800(this);
            preSendTime = DateTime.Now;
            base.setAtHandler(at);


        }


        public override bool deleteMessage(InboundMessage msg)
        {
            lock (getModemDriver().getSYNCCommander())
            {
                if (getStatus() != GatewayStatuses.STARTED) return false;

                return getATHandler().deleteMessage(msg.getMemIndex(), msg.getMemLocation());
            }
        }

        private DateTime preSendTime;
        public override bool sendMessage(org.smslib.OutboundMessage msg)
        {

            if (getStatus() != GatewayStatuses.STARTED) return false;
            long timeLong = DateTime.Now.Ticks - preSendTime.Ticks;
            long sleepTime = 4000 - timeLong / 10000;
            if (sleepTime > 0)
            {
                Thread.Sleep((int)sleepTime);
                Debug.WriteLine("sleep time" + sleepTime.ToString());
            }
            lock (getModemDriver().getSYNCCommander())
            {


                if (msg.getText() == SmsHelper.IsCallNum)
                {
                    bool re = bool.Parse(getATHandler().sendCustomATCommand(msg.getRecipient()));
                    if (re)
                    {
                        msg.setMessageStatus(org.smslib.OutboundMessage.MessageStatuses.SENT);
                        msg.setFailureCause(org.smslib.OutboundMessage.FailureCauses.NO_ERROR);
                    }
                    return re;
                }


                preSendTime = DateTime.Now;

                if (getProtocol() == Protocols.PDU) return sendMessagePDU(msg);
                else if (getProtocol() == Protocols.TEXT) return sendMessageTEXT(msg);
            }
            return true;
        }
        private bool sendMessageTEXT(org.smslib.OutboundMessage msg)
        {
            throw new NotImplementedException();
        }

        private bool sendMessagePDU(org.smslib.OutboundMessage msg)
        {
            //string userData = "看地方都是";


            int refNo = getATHandler().sendMessage(1, msg.getText(), msg.getRecipient(), msg.getText());
            if (refNo >= 0)
            {
                msg.setGatewayId(getGatewayId());
                msg.setRefNo(refNo.ToString());
                DateTime now = DateTime.Now;
                java.util.Date date = new java.util.Date(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                msg.setDispatchDate(date);
                msg.setMessageStatus(org.smslib.OutboundMessage.MessageStatuses.SENT);
                msg.setFailureCause(org.smslib.OutboundMessage.FailureCauses.NO_ERROR);
                incOutboundMessageCount();

            }
            else
            {
                msg.setGatewayId(getGatewayId());
                msg.setRefNo(null);
                DateTime now = DateTime.Now;
                java.util.Date date = new java.util.Date(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second);
                msg.setDispatchDate(date);
                msg.setMessageStatus(org.smslib.OutboundMessage.MessageStatuses.FAILED);
                msg.setFailureCause(org.smslib.OutboundMessage.FailureCauses.UNKNOWN);

                //  msg.setErrorMessage(ge .getLastErrorText());
            }
            return true;
        }

        public override void startGateway()
        {
            //Console.WriteLine("Start GateWay");
            //try
            //{

            base.startGateway();

            //}
            //catch (Exception ex)
            //{
            //    Logger.Write(ex);
            //    DevExpress.XtraEditors.XtraMessageBox.Show("短信猫启动失败!" + this.getGatewayId());

            //}

        }
        //public override AModemDriver getModemDriver()
        //{
        //    return base.getModemDriver();
        //}

        public override void readMessages(java.util.Collection msgList, org.smslib.InboundMessage.MessageClasses msgClass)
        {
            //  return;
            if (this.getStatus() == AGateway.GatewayStatuses.STARTED)
            {


                lock (getModemDriver().getSYNCCommander())
                {
                    if (this.getStatus() == AGateway.GatewayStatuses.STARTED)
                    {
                        if (this.getProtocol() == AGateway.Protocols.PDU)
                        {
                            this.readMessagesPDU(msgList, msgClass, 0);
                        }
                        else if (this.getProtocol() == AGateway.Protocols.TEXT)
                        {
                            // this.readMessagesTEXT(msgList, msgClass, 0);
                        }
                        //  Monitor.Exit(obj2);
                    }
                }
            }

            //base.readMessages(msgList, msgClass);
        }


        private void readMessagesPDU(java.util.Collection msgList, InboundMessage.MessageClasses msgClass, int p)
        {


            try
            {
                string respond = getAtHandler().listMessages(msgClass);
                int count = int.Parse(respond);
                if (count > 0)
                {
                    for (int i = 0; i < count; i++)
                    {
                        respond = getAtHandler().getMessageByIndex(0);
                        if (string.IsNullOrWhiteSpace(respond))
                        {
                            return;
                        }
                        string[] content = respond.Split(',');
                        if (content.Length < 5)
                        {
                            return;
                        }
                        string result = string.Empty;
                        string userData = content[4];
                        if (userData.Length > 2)
                        {
                            userData = userData.Substring(2, userData.Length - 2);
                        }

                        //int len = Convert.ToInt32(userData, 16) * 2;
                        int len = userData.Length;
                        //四个一组，每组译为一个USC2字符
                        for (int ii = 0; ii < len; ii += 4)
                        {
                            try
                            {
                                string temp = userData.Substring(ii, 4);

                                int byte1 = Convert.ToInt16(temp, 16);

                                result += ((char)byte1).ToString();
                            }
                            catch (Exception ex2)
                            {
                                Logger.Write(ex2);
                                continue;
                            }
                        }
                        if (content[1].Length > 2)
                        {
                            content[1] = content[1].Substring(2, content[1].Length - 2);
                        }
                        DateTime now = DateTime.Now;
                        java.util.Date d = new java.util.Date(now.Year, now.Month, now.Day, now.Hour, now.Minute);
                        InboundMessage inMes = new InboundMessage(d, content[1], result, 0, "0");
                        inMes.setGatewayId(this.getGatewayId());
                        msgList.add(inMes);
                        incInboundMessageCount();
                    }
                }

                return;
                if (string.IsNullOrEmpty(respond))
                {
                    return;
                }
                Match m = null;
                try
                {
                    Regex ex = new Regex("([F,N,O,V,U],)*[F,N,O,V,U]\\.");
                    m = ex.Match(respond);
                    if (!m.Success)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                    return;
                }
                if (m == null)
                {
                    return;
                }

                string line = m.ToString();
                if (string.IsNullOrWhiteSpace(line))
                {
                    return;
                }
                string[] info = line.Split(',');
                for (int i = 0; i < info.Length; i++)
                {
                    if (info[i] == "N" || (readTimes == 0 && info[i] == "O"))
                    {
                        try
                        {
                            respond = getAtHandler().getMessageByIndex(i);
                            string line2;
                            int start2, j2;
                            start2 = respond.IndexOf("+CMGR:");
                            if (start2 < 0)
                            {
                                return;
                            }
                            start2 = start2 + 7;
                            j2 = respond.IndexOf("OK");
                            j2 = j2 - 1;
                            line2 = respond.Substring(start2, j2 - start2);
                            string[] content = line2.Split(',');
                            string result = string.Empty;
                            if (content.Length < 6)
                            {
                                return;
                            }

                            string userData = content[5];

                            //int len = Convert.ToInt32(userData, 16) * 2;
                            int len = userData.Length;
                            //四个一组，每组译为一个USC2字符
                            for (int ii = 0; ii < len; ii += 4)
                            {
                                try
                                {
                                    string temp = userData.Substring(ii, 4);

                                    int byte1 = Convert.ToInt16(temp, 16);

                                    result += ((char)byte1).ToString();
                                }
                                catch (Exception ex2)
                                {
                                    Logger.Write(ex2);
                                    continue;
                                }
                            }

                            DateTime now = DateTime.Now;
                            java.util.Date d = new java.util.Date(now.Year, now.Month, now.Day, now.Hour, now.Minute);
                            InboundMessage inMes = new InboundMessage(d, content[1], result, i, i.ToString());
                            inMes.setGatewayId(this.getGatewayId());
                            msgList.add(inMes);
                            incInboundMessageCount();
                        }
                        catch (Exception redex)
                        {
                            Logger.Write(redex);
                            Debug.WriteLine("读取消息异常" + redex.ToString());
                        }
                    }
                }


            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
            finally
            {
                readTimes++;
            }


        }


    }
}
